﻿#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

#include<cstdio>
#include<cstdlib>
#include<conio.h>
#define getpch(type) (type*)malloc(sizeof(type))
struct pcb {
	char name[10];
	char state;
	int super;
	int ntime;
	int rtime;
	struct pcb* link;
}*ready = NULL, * p;
typedef struct pcb PCB;


void sort()
{
	PCB* first, * second;
	int insert = 0;
	if ((ready == NULL) || ((p->super) > (ready->super)))
	{
		p->link = ready;
		ready = p;
	}
	else
	{
		first = ready;
		second = first->link;
		while (second != NULL)
		{
			if ((p->super) > (second->super))
			{
				p->link = second;
				first->link = p;
				second = NULL;
				insert = 1;
			}
			else
			{
				first = first->link;
				second = second->link;
			}
		}
		if (insert == 0)
			first->link = p;
	}
}

void input()
{
	int i, num;
	system("cls");
	/*清屏*/
	cout << "\n   请输入进程号 : ";
	scanf("%d", &num);
	for (i = 0; i < num; i++)
	{
		cout << "\n  进程号 No. :";
		cout << i<<endl;
		p = getpch(PCB);
		cout << "\n   输入进程名:";
		scanf("%s", p->name);
		cout << "\n   输入进程优先数 :";
		scanf("%d", &p->super);
		cout << "\n   输入进程运行时间 :";
		scanf("%d", &p->ntime);
		cout << "\n";
		p->rtime = 0; p->state = 'w';
		p->link = NULL;
		sort();
	}
}
int space()
{
	int l = 0; PCB* pr = ready;
	while (pr != NULL)
	{
		l++;
		pr = pr->link;
	}
	return(l);
}
void disp(PCB* pr)
{
	cout << "\n qname \t state \t super \t ndtime \t runtime \n";
	cout << "  | ";
	cout << pr->name;
	cout << "\t ";
	cout << "  | ";
	cout << pr->state;
	cout << "\t ";
	cout << "  | ";
	cout << pr->super;
	cout << "\t ";
	cout << "  | ";
	cout << pr->state;
	cout << "\t ";
	cout << "  | ";
	cout << pr->rtime;
	cout << "\t ";
	cout << endl;
}

void check()
{
	PCB* pr = NULL;
	cout <<" \n  ****当前正在运行的进程是 : ";
	cout << p->name;
	disp(p);
	pr = ready;
	cout <<"\n  * ***当前就绪队列状态为:\n";
	while (pr != NULL)
	{
		disp(pr);
		pr = pr->link;
	}
}
void destroy()
{
	cout << "\n  进程  [";
	cout << p->name;
	cout << "]  已完成.\n";
	free(p);
}
void running()
{
	(p->rtime)++;
	if (p->rtime == p->ntime)
		destroy();
	else
	{
		(p->super)--;
		p->state = 'w';
		;
		sort();
	}
}
int main()
{
	int len, h = 0;
	char ch;
	input();
	len = space();
	while ((len != 0) && (ready != NULL))
	{
		ch = getchar();
		h++;
		printf("\n The execute number: %d \n", h);
		p = ready;
		ready = p->link;
		p->link = NULL;
		p->state = 'R';
		check();
		running();
		printf("\n 按任一键继续...  ");
		ch = getchar();
	}
	printf("\n\n  进程已经完成.\n");
	ch = getchar();
	system("pause");
	return 0;
}